﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using ExitGames.Client.Photon.Lite;
using DICE_GS;

public class WaitingRoomSceneManager : LTEventListenerC
{
	private static WaitingRoomSceneManager instance;

	public static WaitingRoomSceneManager Instance{
		get{
			return instance;
		}
	}	

	void Awake()
	{
		instance = this;
	}
	
	public UISprite singleTab;
	public UISprite multiTab;
	public UILabel[] hpPotionCount;
	public UILabel[] resurrectPotionCount;
	
	public MyUnitCard[] myUnitCards;
	
	public UISprite[] deckButtonImages;
	
    private static Queue<Dictionary<byte, object>> packetQueue = new Queue<Dictionary<byte, object>>();

	public MapListManager mapListManager;
	
	public UISprite[] skillIcon;
	
	public GameObject BattleMateSeleceWindow;
	
	public GameObject PvPDirectEnterRoomButton;
	public GameObject PvPCreateRoomButton;
	public GameObject singleGameStartButton;

	void Start()
	{
		_oldDeckIndex = MyInfo.Instance.MyCurrentDeck;
		SetSingleMultiTab();
//		MyInfo.Instance.SetMyUnitDeckImg();
		SetMyDeckInfo();
		foreach(UILabel label in hpPotionCount)
			label.text = "x"+MyInfo.Instance.HPPotion.ToString();
		foreach(UILabel label in resurrectPotionCount)
			label.text = "x"+MyInfo.Instance.ResurrectPotion.ToString();
	}
	
	public void SetSingleMultiTab()
	{
		if(CSceneManager.isSingleGame) {
			singleTab.spriteName = "UI_btn02";
			multiTab.spriteName = "UI_btn03";
			PvPDirectEnterRoomButton.SetActive(false);
			PvPCreateRoomButton.SetActive(false);
			singleGameStartButton.SetActive(true);
			mapListManager.SelectSingleMapTap();
		}
		else {
			singleTab.spriteName = "UI_btn03";
			multiTab.spriteName = "UI_btn02";	
			PvPDirectEnterRoomButton.SetActive(true);
			PvPCreateRoomButton.SetActive(true);
			singleGameStartButton.SetActive(false);
			mapListManager.SelectMultiMapTap();
		}		
	}

    // Update is called once per frame
    void Update()
    {
        while (packetQueue.Count > 0)
        {
            Dictionary<byte, object> tmpPacket = packetQueue.Dequeue();

            switch ((byte)tmpPacket[0])
            {
                default:
                    glog.debug("WaitingRoomSceneManager's Packet Handler Unknown Packet Recieved [" + (byte)tmpPacket[0] + "]");
                    break;
            }
        }
    }

	void OnGoToDeckEditScene()
	{
		CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
		c.GoToDeckEditScene();
	}

    public static bool PacketHandler(Dictionary<byte, object> _packet)
    {
        glog.debug("WaitingRoomSceneManager Got Packet");
        if (packetQueue != null)
        {
            packetQueue.Enqueue(_packet);
            return true;
        }

        return false;
    }

    public void LeftArrowClicked()
    {
		int OldDeckIndex = MyInfo.Instance.MyCurrentDeck;

        if (--MyInfo.Instance.MyCurrentDeck < 0)
        {
            MyInfo.Instance.MyCurrentDeck = MyInfo.Instance.MyDeckMap.Count-1;
        }

        LoadingWindow.window.ShowShortLoading();
		MyInfo.Instance.MyDeckMap[OldDeckIndex].order = 0;
		RestAPI.singleton.SendMyDeckChangeInfo(ReturnCallback, MyInfo.Instance.MyDeckMap[OldDeckIndex].deckId);
		MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].order = 1;
		RestAPI.singleton.SendMyDeckChangeInfo(ReturnCallback, MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].deckId);

        
    }

    public void RightArraowClicked()
    {
		int OldDeckIndex = MyInfo.Instance.MyCurrentDeck;

        if (++MyInfo.Instance.MyCurrentDeck > MyInfo.Instance.MyDeckMap.Count-1)
        {
            MyInfo.Instance.MyCurrentDeck = 0;
        }

        LoadingWindow.window.ShowShortLoading();
		MyInfo.Instance.MyDeckMap[OldDeckIndex].order = 0;
		RestAPI.singleton.SendMyDeckChangeInfo(ReturnCallback, MyInfo.Instance.MyDeckMap[OldDeckIndex].deckId);
		MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].order = 1;
		RestAPI.singleton.SendMyDeckChangeInfo(ReturnCallback, MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].deckId);
    }
	
	public void SetMyDeckInfo()
	{
		int currentExistDeckCardCount = 0;
		
		for(int i=0; i<5; i++)
		{
			if( MyInfo.Instance.MyDeckMap.ContainsKey(i) )
			{
				if( i == MyInfo.Instance.MyCurrentDeck )
					deckButtonImages[i].spriteName = "UI_btn02s";
				else
					deckButtonImages[i].spriteName = "UI_btn03s";
			}
			else
			{
				deckButtonImages[i].transform.parent.gameObject.SetActive(false);
			}
		}
		
		if (MyInfo.Instance.MyDeckMap.ContainsKey(MyInfo.Instance.MyCurrentDeck))
		{
			DeckInfo tmpDeck = MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck];
			if (tmpDeck != null)
			{
				foreach (KeyValuePair<int, UnitInfo> pair in tmpDeck.SlotMap)
				{
					if (pair.Value != null)
                    {
                        foreach (UnitInfo info in MyInfo.Instance.MyUnitsList)
                        {
                            if (info.UnitDBID == pair.Value.UnitDBID)
                            {
                                pair.Value.UnitClassID = info.UnitClassID;
                                break;
                            }
                        }
                        CUnitData tmpUnitData = CUnitDataManager.Instance.GetUnitData(pair.Value.UnitClassID);

                        if (tmpUnitData != null)
                        {
							myUnitCards[pair.Key].gameObject.SetActive(true);
							myUnitCards[pair.Key].slot.SetActive(true);
							myUnitCards[pair.Key].blankSlot.SetActive(false);
                            myUnitCards[pair.Key].SetCardInfo(pair.Key, pair.Value);
							myUnitCards[pair.Key].CreateDummyCard();
							currentExistDeckCardCount++;
//							TweenRotation rotation = TweenRotation.Begin(myUnitCards[pair.Key].gameObject, 0.2f, Quaternion.Euler(new Vector3(0f,0f,0f)));
//							myUnitCards[pair.Key].transform.localRotation = Quaternion.Euler(new Vector3(0f, 0f, 0f));
                        }
                        else
                        {
							myUnitCards[pair.Key].gameObject.SetActive(true);
							myUnitCards[pair.Key].slot.SetActive(false);
							myUnitCards[pair.Key].blankSlot.SetActive(true);
							myUnitCards[pair.Key].HideDummyCard();
//							myUnitCards[pair.Key].transform.localRotation = Quaternion.Euler(new Vector3(0f, 0f, 0f));
                        }
//						TweenRotation rotation2 = TweenRotation.Begin(myUnitCards[pair.Key].gameObject, 0.2f, Quaternion.Euler(new Vector3(0f,0f,0f)));
						myUnitCards[pair.Key].sceneManager = this;
                    }
                    else
                    {
                        Debug.LogError("null");
                    }
				}
				
				skillIcon[0].spriteName = tmpDeck.skill1_IconName;
				skillIcon[1].spriteName = tmpDeck.skill2_IconName;
			}
		}
	}
	
	int dragDirection;
	public bool isDragging = false;
	public void Drag(int index, Vector2 delta)
	{
		if( isDragging == false)
		{
			dragDirection = delta.x < 0 ? -1 : 1;
			foreach(MyUnitCard card in myUnitCards)
			{
//				if( card.gameObject.activeSelf ) 
//				{
					Debug.LogError("rotation!");
					card.HideDummyCard();
					TweenRotation rotation = TweenRotation.Begin(card.gameObject, 0.2f, Quaternion.Euler(new Vector3(0f,0f,0f)));
					EventDelegate.Add(rotation.onFinished, OnRotationFinished, true);
//				}
			}
		}
		isDragging = true;
	}
				

	void ReturnCallback(Hashtable returnData)
	{
        LoadingWindow.window.HideLoading();
		SetMyDeckInfo();
	}
				
	void OnRotationFinished()
	{
		_oldDeckIndex = MyInfo.Instance.MyCurrentDeck;
		if( dragDirection > 0 )
		{
			MyInfo.Instance.MyCurrentDeck -= 1;
			if( MyInfo.Instance.MyCurrentDeck < 0 )
				MyInfo.Instance.MyCurrentDeck = MyInfo.Instance.MyDeckMap.Count-1;
			SetMyDeckInfo();
		}
		else
		{
			MyInfo.Instance.MyCurrentDeck += 1;
			if( MyInfo.Instance.MyCurrentDeck > MyInfo.Instance.MyDeckMap.Count-1 )
				MyInfo.Instance.MyCurrentDeck = 0;
			SetMyDeckInfo();
		}
	}
	
	int _oldDeckIndex = 0;
	public int oldDeckIndex
	{
		get
		{
			return _oldDeckIndex;
		}
	}
	
	public override void OnEvent (int eventID)
	{
		base.OnEvent (eventID);
		
		_oldDeckIndex = MyInfo.Instance.MyCurrentDeck;
		MyInfo.Instance.MyCurrentDeck = eventID;
		
//		MyInfo.Instance.MyDeckMap[_oldDeckIndex].order = 0;
//		RestAPI.singleton.SendMyDeckChangeInfo(ReturnCallback, MyInfo.Instance.MyDeckMap[OldDeckIndex].deckId);
//		MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].order = 1;
//		RestAPI.singleton.SendMyDeckChangeInfo(ReturnCallback, MyInfo.Instance.MyDeckMap[MyInfo.Instance.MyCurrentDeck].deckId);
		
		for(int i=0; i<MyInfo.Instance.MyDeckMap.Count; i++)
		{
			if( i == MyInfo.Instance.MyCurrentDeck )
				deckButtonImages[i].spriteName = "UI_btn02s";
			else
				deckButtonImages[i].spriteName = "UI_btn03s";
		}		
		SetMyDeckInfo();
	}
	
	public bool isChangedDeck
	{
		get
		{
			return _oldDeckIndex == MyInfo.Instance.MyCurrentDeck ? false : true;
		}
	}
	
	public void ShowBattleMateListWindow()
	{
		BattleMateSeleceWindow.SetActive(true);
	}
	
	public void HideBattleMateListWindow()
	{
		BattleMateSeleceWindow.SetActive(false);
	}
}
